package com.ideaaedi.zoo.example.springboot.sse.callback;

import com.ideaaedi.commonds.time.DateTimeConverter;
import com.ideaaedi.zoo.diy.artifact.sse.core.SsePusher;
import com.ideaaedi.zoo.diy.artifact.sse.core.SsePusherCallback;
import com.ideaaedi.zoo.example.springboot.sse.util.SseUidUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.MDC;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.nio.charset.StandardCharsets;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 回调分布式统一管理会话id
 */
@Slf4j
@Component
@EnableScheduling // 确保启用了@Scheduled
public class DemoSsePusherCallback implements SsePusherCallback {
    
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    
    @Override
    public void onPut(String emitterUuid, SseEmitter sseEmitter) {
        String redisKey = SseUidUtil.buildEmitterUuidRedisKey(emitterUuid);
        stringRedisTemplate.opsForValue().set(
                redisKey,
                DateTimeConverter.COMPACT_DATE_TIME.now(),
                // 过期时间（需要要比sse看门狗执行周期长）
                25, TimeUnit.HOURS
        );
    }
    
    @Override
    public void onRemove(String emitterUuid) {
        String redisKey = SseUidUtil.buildEmitterUuidRedisKey(emitterUuid);
        stringRedisTemplate.delete(redisKey);
    }
    
    /**
     * 看门狗 for 存在redis中sse唯一标识符，自动续期存活连接的sse唯一标识符、自动清除未存活连接的sse唯一标识符
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void sseWatchdog() {
        log.info("sseWatchdog start.");
        long now = System.currentTimeMillis();
        String traceXd = "traceXd";
        MDC.put(traceXd, "sseWatchdog_" + now);
        try {
            Pair<Set<String>, Set<Pair<String, Throwable>>> pair = SsePusher.aliveStatus();
            Set<String> aliveEmitterUuidSet = pair.getLeft();
            Set<Pair<String, Throwable>> diedEmitterUuidSet = pair.getRight();
            // 续期存活连接的sse唯一标识符
            if (!CollectionUtils.isEmpty(aliveEmitterUuidSet)) {
                log.info("for redis key, to renewal sse-emitter-uuid -> {}.", aliveEmitterUuidSet);
                for (String emitterUuid : aliveEmitterUuidSet) {
                    String redisKey = SseUidUtil.buildEmitterUuidRedisKey(emitterUuid);
                    // 过期时间（需要要比sse看门狗执行周期长）
                    stringRedisTemplate.expire(redisKey, 25, TimeUnit.HOURS);
                }
            }
            
            // 清除未存活连接的sse唯一标识符
            if (!CollectionUtils.isEmpty(diedEmitterUuidSet)) {
                log.info("for redis key, to delete sse-emitter-uuid -> {}.",
                        diedEmitterUuidSet.stream().map(Pair::getLeft).toList());
                for (Pair<String, Throwable> tmpPair : diedEmitterUuidSet) {
                    String emitterUuid = tmpPair.getLeft();
                    Throwable right = tmpPair.getRight();
                    SsePusher.removeLocalEmitter(emitterUuid, right, this);
                }
            }
            log.info("sseWatchdog end.");
        } catch (Exception e) {
            log.error("sseWatchdog occur exception.", e);
        } finally {
            try {
                MDC.remove(traceXd);
            } catch (Exception ignore) {
            }
        }
    }
    
    /**
     * 根据通配符扫描redis中的key
     *
     * @param pattern 通配
     *                <pre>
     *                如: projectName:userId:*  <br />
     *                注：安全考虑，前置要求pattern不能为*
     *                </pre>
     * @param scanCount 每次扫描的key个数
     *
     * @return redis中的key
     */
    public static LinkedHashSet<String> scan(StringRedisTemplate stringRedisTemplate, String pattern, long scanCount) {
        if (StringUtils.isBlank(pattern)) {
            throw new IllegalArgumentException("pattern cannot be blank.");
        }
        if ("*".equals(pattern)) {
            throw new IllegalArgumentException("pattern cannot be '*'.");
        }
        if (scanCount <= 0) {
            throw new IllegalArgumentException("scanCount cannot le 0.");
        }
        return stringRedisTemplate.execute((RedisCallback<LinkedHashSet<String>>) connection -> {
            LinkedHashSet<String> keys = new LinkedHashSet<>();
            Cursor<byte[]> cursor = connection.scan(
                    ScanOptions.scanOptions().match(pattern).count(scanCount).build()
            );
            while (cursor.hasNext()) {
                keys.add(new String(cursor.next(), StandardCharsets.UTF_8));
            }
            return keys;
        });
    }
}
